<?php
require_once ('utils' . DIRECTORY_SEPARATOR . 'HHAbstract.php');

class HHSBidsProfile extends HHAbstract {
	
	private $profileId;
	private $userId;
	private $profileData;
	private $pastBids;
	private $currentBids;
	
	function __construct() {
		parent::__construct ();
	}
	
	function __destruct() {
		parent::__destruct ();
	}
	
	function constructClass() {
		$this->currentBids = array();
		$this->pastBids = array();
		
		if (isset ( $_REQUEST ['user_id'] )) {
			$this->userId = $_REQUEST ['user_id'];
		}
		
		if (isset ( $_REQUEST ['user_bid_profile_id'] )) {
			$this->loadBidProfile ( $_REQUEST ['user_bid_profile_id'] );
		}
		
		if (isset ( $_REQUEST ['save'] )) {
			$this->saveProfile ();
		}
		
		// Echo the form for a profile
		$form = $this->getHTMLForm ();
		die ( $form );
	
	}
	
	function getHTMLForm() {
		$profileIDPAram = '';
		if (isset ( $this->profileId )) {
			$profileIDPAram .= '&user_bid_profile_id=' . $this->profileId;
		}
		if (isset ( $this->userId )) {
			$profileIDPAram .= '&user_id=' . $this->userId;
		}
		$form = '
		<form method="POST" action="' . basename ( __FILE__ ) . '?save=true' . $profileIDPAram . '">
			Profile Name: ' . $this->getProfileNameInput () . '<br>
			Profile Description:<br>' . $this->getProfileDescriptionInput () . '<br>
			 <fieldset id="bidder_info_fieldset">
			 	<legend>Bidder Info:</legend>
			    Address: ' . $this->getUserAddressesInput () . '
			    <br>
			    Purchase ID: ' . $this->getUserPurchaseIDInput () . '
			 </fieldset>
			 <fieldset id="financial_info_fieldset">
			 	<legend>Financial Info:</legend>
			 	' . $this->getFinancialInfoInputs () . '
			 </fieldset>	
			 <fieldset id="bidding_guidelines_fieldset">
			 	<legend>Bidding Guidelines:</legend>
			 	' . $this->getBiddingGuidelinesInput () . '
			 </fieldset>
			 <fieldset id="scheduled_bids_fieldset">	
			 	<legend>Scheduled Bid:</legend>
			 	' . $this->getScheduledBidsHTML () . '
			 </fieldset>	
			 <fieldset id="past_bids_fieldset">
			 	<legend>Past Bids:</legend>
			 	' . $this->getPastBidsHTML () . '
			 </fieldset>
			  <input type="submit" value="SAVE">
		</form>
		';
		
		return $form;
	}
	
	function getPastBidsHTML() {
		$this->getPastBids ();
		$html = '<table id="past_bids_table" border=1>
		<thead>
		<td>Confirmation<br>Number</td>
		<td>Property<br>Case</td>
		<td>Purchaser<br>SSN/EIN/ID</td>
		<td>Purchaser<br>Type</td>
		<td>Net Bid<br>Amount</td>
		<td>Bid<br>Status</td>
		<td>Bid Open<br>Date</td>
		<td>Counter<br>Offer</td>
		<td>Original<br>Bid</td>
		</thead>
		<tbody>
		';
		
		foreach ( $this->pastBids as $case => $caseArray ) {
			foreach ( $caseArray as $bidData ) {
				//var_dump($bidData);
				
				$query = 'Select type, value from user_purchase_ids WHERE id='.$bidData['user_purchase_id'];
				$result = $this->runQuery ( $query, $this->getDBConnection ()->getDBConnection () );
				$row = $result->fetch_assoc ();
				$userPurchaseId = $row ['value'];
				if (stripos ( $row ['type'], 'ssn' ) !== false) {
					$userPurchaseId = 'XXX-XX-' . substr ( $userPurchaseId, - 4, 4 );
				}
				$counterOffer = ((bool)$bidData['has_counter_offer'])? 'Yes':'No';
				
				$html .= '<tr>';
				$html .= '<td>'.$bidData['confirmation_number'].'</td>';
				$html .= '<td>'.$case.'</td>';
				$html .= '<td>'.$userPurchaseId.'</td>';
				$html .= '<td>'.$bidData['purchaser_type'].'</td>';
				$html .= '<td>'.$bidData['bid_amount'].'</td>';
				$html .= '<td>'.$bidData['bid_status'].'</td>';
				$html .= '<td>'.$bidData['submission_time'].'</td>';
				$html .= '<td>'.$counterOffer.'</td>';
				$html .= '<td>?</td>';
				$html .= '</tr>';
			}
		}
		
		$html .= '</tbody></table>';
		return $html;
	
	}
	
	function getScheduledBidsHTML() {
		$this->getCurrentBids ();
		$html = '<table id="current_bids_table" border=1>
		<thead>
		<td>Property<br>Case</td>
		<td>Purchaser<br>Type</td>
		<td>Bid<br>Amount</td>
		<td>Seller Closing<br>Cost</td>
		<td>Broker Commission<br>Cost</td>
		<td>Used As<br>Backup Offer</td>
		<td>Scheduled<br>Submit Date</td>
		<td>User<br>Confirmed</td>
		</thead>
		<tbody>
		';
		
		foreach ( $this->currentBids as $case => $caseArray ) {
			foreach ( $caseArray as $bidData ) {
				//var_dump($bidData);
				$html .= '
				<tr>
				<td><input type="text" name="bid[' . $bidData ['id'] . '][case]" value="' . $bidData ['case'] . '" readonly></td>';
	
				$purchaserTypeChecked = array ('O' => '', 'I' => '', 'N' => '', 'G' => '' );
				$purchaserTypeChecked[$bidData['purchaser_type']?:'I'] = 'selected';	
				$html .= '<td><select name="bid[' . $bidData ['id'] . '][purchaser_type]">
				<option value="O" '.$purchaserTypeChecked['O'].'>Owner-Occupant</option>
				<option value="I" '.$purchaserTypeChecked['I'].'>Investor</option>
				<option value="N" '.$purchaserTypeChecked['N'].'>Nonprofit Organization</option>
				<option value="G" '.$purchaserTypeChecked['G'].'>Other Government Agency</option>
				</select>
				</td>';
				
				$html .= '
				<td><input type="text" name="bid[' . $bidData ['id'] . '][bid_amount]" value="' . $bidData ['bid_amount'] . '"></td>
				<td><input type="text" name="bid[' . $bidData ['id'] . '][seller_closing_cost]" value="' . $bidData ['seller_closing_cost'] . '"></td>
				<td><input type="text" name="bid[' . $bidData ['id'] . '][broker_commission_cost]" value="' . $bidData ['broker_commission_cost'] . '"></td>';
					
					if (! isset ( $bidData ['accept_as_backup_offer'] ) || (( int ) $bidData ['accept_as_backup_offer']) == - 1) {
						$backUpOfferChecked = array ('-1' => 'checked', '0' => '' );
					} else {
						$backUpOfferChecked = array ('-1' => '', '0' => 'checked' );
					}
					
					$html .= '
				<td>Yes<input type="radio" name="bid[' . $bidData ['id'] . '][accept_as_backup_offer]" value="-1" ' . $backUpOfferChecked ['-1'] . '>
				<br>No<input type="radio" name="bid[' . $bidData ['id'] . '][accept_as_backup_offer]" value="0" ' . $backUpOfferChecked ['0'] . '></td>';
					
					$html .= '
				<td><input type="text" name="bid[' . $bidData ['id'] . '][scheduled_submission_time]" value="' . $bidData ['scheduled_submission_time'] . '"></td>';
					
					
					$isBidUserConfirmed = ( bool ) ($bidData ['user_confirmed']?:false);
					$userConfirmed = '';
					if ($isBidUserConfirmed==true) {
						$userConfirmed = 'checked';
					}
					
					// TODO: Delete Below (Make all bids selected as confirmed)
					//$userConfirmed = 'checked';
					
					$html .= '
				<td><input type="checkbox" name="bid[' . $bidData ['id'] . '][user_confirmed]" ' . $userConfirmed . ' value=1></td>
				</tr>
				';
			}
		}
		$html .= '</tbody></table>';
		return $html;
	}
	
	function getBiddingGuidelinesInput() {
		$inputs = 'Cases: <select multiple=true id="cases" name="cases[]">';
		$cases = array ();
		if (isset ( $this->profileData ['cases'] )) {
			$cases = json_decode ( $this->profileData ['cases'], true );
		}
		$cases = array_unique($cases);
		foreach ( $cases as $key => $value ) {
			$inputs .= '<option value="' . $value . '" SELECTED=true>' . $value . '</option>';
		}
		$inputs .= '</select>
		Add Case: <textarea id="new_case" name="new_case"></textarea>
		<input type="button" value="Add Case" onClick="
		var cases = document.getElementById(\'cases\');
		var nCases = document.getElementById(\'new_case\');
		var txtValue = nCases.value;
		var nCasesArray = txtValue.replace( /\\n/g, \' \' ).split( \' \' );
		for(key in nCasesArray ){
			var nCase = nCasesArray[key];
			cases.innerHTML += \'<option selected=true value=\\\'\'+nCase+\'\\\'>\'+nCase+\'</option>\';
		}
		nCases.value = \'\';
		">	
		<br>';
		
		$inputs .= 'Zip Codes <select multiple=true id="zip_codes" name="zip_codes[]">';
		$zipCodes = array ();
		if (isset ( $this->profileData ['zip_codes'] )) {
			$zipCodes = json_decode ( $this->profileData ['zip_codes'], true );
		}
		foreach ( $zipCodes as $key => $value ) {
			$inputs .= '<option value="' . $value . '" SELECTED=true>' . $value . '</option>';
		}
		$inputs .= '</select>
		Add Zip Code: <input type="text" id="new_zip_code" name="new_zip_code">
		<input type="button" value="Add Zip Code" onClick="
		var zipCodes = document.getElementById(\'zip_codes\');
		var nZipCode = document.getElementById(\'new_zip_code\');
		zipCodes.innerHTML += \'<option selected=true value=\\\'\'+nZipCode.value+\'\\\'>\'+nZipCode.value+\'</option>\';
		nZipCode.value = \'\';
		">	
		<br>
		
		
		Zip Code Range (miles): <input type="text" name="zip_code_range" id="zip_code_range" value="' . $this->profileData ['zip_code_range'] . '"><br>
		
		Min Bid Price: <input type="text" name="bid_price_min" id="bid_price_min" value="' . $this->profileData ['bid_price_min'] . '"><br>
		Max Bid Price: <input type="text" name="bid_price_max" id="bid_price_max" value="' . $this->profileData ['bid_price_max'] . '"><br>
		Min Bid Percentage (% of Net To Hud): <input type="text" name="bid_price_min_percentage" id="bid_price_min_percentage" value="' . $this->profileData ['bid_price_min_percentage'] . '"><br>
		Max Bid Percentage (% of Net To Hud): <input type="text" name="bid_price_max_percentage" id="bid_price_max_percentage" value="' . $this->profileData ['bid_price_max_percentage'] . '"><br>
		Bid Price Increment: <input type="text" name="bid_price_increase" id="bid_price_increase" value="' . $this->profileData ['bid_price_increase'] . '"><br>
		Bid Price % Increment (% of Net To Hud): <input type="text" name="bid_price_percentage_increase" id="bid_price_percentage_increase" value="' . $this->profileData ['bid_price_percentage_increase'] . '"><br>
		
		';
		
		return $inputs;
	}
	
	function getFinancialInfoInputs() {
		$financeTypeChecked = array_fill ( 0, 4, '' );
		$financeTypeChecked[((int)$this->profileData['finance_type'])?:0] = 'checked';
		
		$inputs = 'Purchaser Is:<br> 
		<input type="radio" value="2" name="finance_type" id="finance_type" ' . $financeTypeChecked [2] . '>applying for HUD/FHA insured financing 203(b) involved.<br>
		<input type="radio" value="3" name="finance_type" id="finance_type" ' . $financeTypeChecked [3] . '>applying for HUD/FHA insured financing 203(b) repair escrow involved.<br>
		<input type="radio" value="1" name="finance_type" id="finance_type" ' . $financeTypeChecked [1] . '>applying for HUD/FHA insured financing 203(k) involved.<br>
		<input type="radio" value="0" name="finance_type" id="finance_type" ' . $financeTypeChecked [0] . '>paying cash, or applying for conventional or other financing not involving HUD/FHA<br>';
		
		$purchaserTypeChecked = array ('O' => '', 'I' => '', 'N' => '', 'G' => '' );
		$purchaserTypeChecked[$this->profileData['purchaser_type']?:'I'] = 'checked';
		$inputs .= 'Purchaser Is:<br> 
		<input type="radio" value="O" name="purchaser_type" id="purchaser_type" ' . $purchaserTypeChecked ['O'] . '>Owner-Occupant (will occupy this property as primary residence)<br>
		<input type="radio" value="I" name="purchaser_type" id="purchaser_type" ' . $purchaserTypeChecked ['I'] . '>Investor<br>
		<input type="radio" value="N" name="purchaser_type" id="purchaser_type" ' . $purchaserTypeChecked ['N'] . '>Nonprofit Organization (should be a HUD approved Non Profit Agency)<br>
		<input type="radio" value="G" name="purchaser_type" id="purchaser_type" ' . $purchaserTypeChecked ['G'] . '>Other Government Agency<br>';
		
		$inputs .= 'Seller Closing Cost: <input type="text" value="' . $this->profileData ['seller_closing_cost'] . '" name="seller_closing_cost" id="seller_closing_cost"><br>';
		$inputs .= 'Seller Closing Cost % (% of Bid Price): <input type="text" value="' . $this->profileData ['seller_closing_cost_percentage'] . '" name="seller_closing_cost_percentage" id="seller_closing_cost_percentage"><br>';
		$inputs .= 'Broker Commission Cost: <input type="text" value="' . $this->profileData ['broker_commission_cost'] . '" name="broker_commission_cost" id="broker_commission_cost"><br>';
		$inputs .= 'Broker Commission Cost % (% of Bid Price): <input type="text" value="' . $this->profileData ['broker_commission_cost_percentage'] . '" name="broker_commission_cost_percentage" id="broker_commission_cost_percentage"><br>';
		
		if (! isset ( $this->profileData ['accept_as_backup_offer'] ) || (( int ) $this->profileData ['accept_as_backup_offer']) == - 1) {
			$backUpOfferChecked = array ('-1' => 'checked', '0' => '' );
		} else {
			$backUpOfferChecked = array ('-1' => '', '0' => 'checked' );
		}
		
		//die('Accept: '.$this->profileData['accept_as_backup_offer']);
		//$backUpOfferChecked[$this->profileData['accept_as_backup_offer']?:'-1'] = 'checked';
		$inputs .= 'If seller does not accept this offer. Seller<br> 
		<input type="radio" value=-1 name="accept_as_backup_offer" id="accept_as_backup_offer" ' . $backUpOfferChecked ['-1'] . '>may hold such offer as a back-up to accepted offer<br>
		<input type="radio" value=0 name="accept_as_backup_offer" id="accept_as_backup_offer" ' . $backUpOfferChecked ['0'] . '>may not hold such offer as a back-up to accepted offer<br>';
		
		return $inputs;
	}
	
	function getProfileNameInput() {
		$profileInput = '<input type="text" name="profile_name" id="profile_name"';
		if (isset ( $this->profileData ) && isset ( $this->profileData ['profile_name'] )) {
			$profileInput .= ' value="' . $this->profileData ['profile_name'] . '"';
		}
		$profileInput .= '>';
		return $profileInput;
	}
	
	function getProfileDescriptionInput() {
		$profileInput = '<textarea name="profile_description" id="profile_description">';
		if (isset ( $this->profileData ) && isset ( $this->profileData ['profile_description'] )) {
			$profileInput .= $this->profileData ['profile_description'];
		}
		$profileInput .= '</textarea>';
		return $profileInput;
	}
	
	function getUserPurchaseIDInput() {
		$input = '<select name="user_purchase_id_id" id="user_purchase_id_id">';
		if ((isset ( $this->profileData ) && isset ( $this->profileData ['user_purchase_id_id'] )) || isset ( $this->userId )) {
			$query = 'Select * from user_purchase_ids WHERE user_id='.($this->profileData['user_id']?:$this->userId);
			$result = $this->runQuery ( $query, $this->getDBConnection ()->getDBConnection () );
			$isOptionSelected = false;
			while ( ($row = $result->fetch_assoc ()) ) {
				$selected = '';
				if (isset ( $this->profileData ['user_purchase_id_id'] ) && $this->profileData ['user_purchase_id_id'] == $row ['id']) {
					$selected = ' SELECTED=TRUE ';
					$isOptionSelected = true;
				} else if ($isOptionSelected == false && (( bool ) $row ['is_default'])) {
					$selected = ' SELECTED=TRUE ';
					$isOptionSelected = true;
				}
				$value = $row ['value'];
				if (stripos ( $row ['type'], 'ssn' ) !== false) {
					$value = 'XXX-XX-' . substr ( $value, - 4, 4 );
				}
				$input .= '<option value="' . $row ['id'] . '" ' . $selected . '>' . $value . ' (' . $row ['type'] . ')</option>';
			}
		}
		$input .= '</select>';
		return $input;
	}
	
	function getUserAddressesInput() {
		$options = '
		<select name="user_address_id" id="user_address_id" onChange="if(this.value==\'new\'){
		  document.getElementById(\'new_address_fieldset\').style.display=\'block\';
			}else{
			document.getElementById(\'new_address_fieldset\').style.display=\'none\';
			}">';
		$isOptionSelected = false;
		if ((isset ( $this->profileData ) && isset ( $this->profileData ['user_id'] )) || isset ( $this->userId )) {
			$query = 'Select * from user_address WHERE id='.($this->profileData['user_id']?:$this->userId);
			$result = $this->runQuery ( $query, $this->getDBConnection ()->getDBConnection () );
			
			while ( ($row = $result->fetch_assoc ()) ) {
				$selected = '';
				if (isset ( $this->profileData ['user_address_id'] ) && $this->profileData ['user_address_id'] == $row ['id']) {
					$selected = ' SELECTED=TRUE ';
					$isOptionSelected = true;
				} else if ($isOptionSelected == false && (( bool ) $row ['is_default'])) {
					$selected = ' SELECTED=TRUE ';
					$isOptionSelected = true;
				}
				$options .= '<option value="' . $row ['id'] . '" ' . $selected . '>' . $row ['address'] . "\n\r<br>";
				$options .= $row ['city'] . ', ' . $row ['state'] . ' ' . $row ['zip'] . '</option>';
			}
		}
		$options .= '<option value="new">Add New Address</option></select>
		 <fieldset name="new_address_fieldset" id="new_address_fieldset" class="new_address" ';
		if ($isOptionSelected == true) {
			$options .= ' style="display:none"';
		}
		$options .= '>
			 	<legend>New Address:</legend>
			 	Address:<input type="" name=""><br>
			 	City: <select name="city"></select><br>
			 	State: <select name="state"></select><br>
			 	Zip: <input type="text" name="zip">
		</fieldset>	 	
		';
		// Add user id as hidden input field
		if (isset ( $this->userId )) {
			$options .= '<input type="hidden" name="user_id" id="user_id" value="' . $this->userId . '">';
		}
		return $options;
	}
	
	public function loadBidProfile($bidProfileId) {
		$this->profileId = $bidProfileId;
		
		$query = 'Select *
			from user_bids_profiles as ubp 
			WHERE
			ubp.id = ' . $bidProfileId;
		$result = $this->runQuery ( $query, $this->getDBConnection ()->getDBConnection () );
		$this->profileData = $result->fetch_assoc ();
		$this->userId = $this->profileData ['user_id'];
	
	}
	
	function getPastBids() {
		if (isset ( $this->profileId )) {
			$query = 'Select *
				from 
				user_bids as ub
				WHERE
				ub.user_bid_profile_id = ' . $this->profileId . ' AND ub.submission_time IS NOT NULL
				order by ub.submission_time DESC';
			$result = $this->runQuery ( $query, $this->getDBConnection ()->getDBConnection () );
			while ( ($row = $result->fetch_assoc ()) ) {
				if (! isset ( $this->pastBids [$row ['case']] )) {
					$this->pastBids [$row ['case']] = array ();
				}
				$this->pastBids [$row ['case']] [] = $row;
			}
		}
	}
	
	function getCurrentBids() {
		if (isset ( $this->profileId )) {
			$query = 'Select *
				from 
				user_bids as ub
				WHERE
				ub.user_bid_profile_id = ' . $this->profileId . ' 
				AND ub.submission_time IS NULL
				AND ub.user_confirmed=1
				order by ub.submission_time DESC';
			$result = $this->runQuery ( $query, $this->getDBConnection ()->getDBConnection () );
			while ( ($row = $result->fetch_assoc ()) ) {
				$case = $row ['case'];
				if (! isset ( $this->currentBids [$case] )) {
					$this->currentBids [$case] = array ();
				}
				$this->currentBids [$case] [] = $row;
			}
			$this->getNewBidsAttachedToCurrentBids();
		}
	}
	
	function getNewBidsAttachedToCurrentBids(){
		if(isset($this->profileData) && (isset($this->profileData['cases']) || isset($this->profileData['zipCodes']) )){
			$cases = json_decode($this->profileData['cases'],true);
			$zipCodes = json_decode($this->profileData['zip_codes'],true);
			$query = 'Select pl.case, pl.price, pl.state from property_list as pl
						LEFT JOIN bid_results as br on br.case = pl.case 
						WHERE ';
			$whereCondition = array('br.case IS NULL');
			if(count($cases)>0){
				if(!isset($whereCondition['case_zipCodes'])){
					$whereCondition['case_zipCodes'] = array();
				}
				$whereCondition['case_zipCodes'][] = 'pl.case in (\''.implode("','",$cases).'\')'; 
			}
			if(count($zipCodes)>0){
				if(!isset($whereCondition['case_zipCodes'])){
					$whereCondition['case_zipCodes'] = array();
				}
				$whereCondition['case_zipCodes'][] = 'pl.zip in (\''.implode("','",$zipCodes).'\')'; 
				
				
			}
			
			// TODO: Delete Below (ALL MD cases)
			//$whereCondition['case_zipCodes'][] = '(pl.state ="MD" and pl.list_period="Extended")';
			
			$whereModified = array();
			foreach ($whereCondition as $index => $condition){
				if(is_array($condition)){
				$whereModified[] = '('.implode(' OR ',$condition).')';
				}else{
					$whereModified[] = $condition;	
				}
			}
			$query.= implode(' AND ',$whereModified);
			
			$query.= ' GROUP BY pl.case 
					  ORDER BY pl.list_date ASC, pl.case ASC, pl.price ASC
			';
			//echo('Additional Bids Query: '.$query.'<br>');
			$result = $this->runQuery ( $query, $this->getDBConnection ()->getDBConnection () );
			while ( ($row = $result->fetch_assoc ()) ) {
				$case = $row['case'];
				$price = $row['price'];
				$state = $row['state'];
				// Check to see if user has a allowed agent_licens to use for the found case
				$query2 = 'Select al.id as agent_license_id 
							from agent_license as al
							INNER JOIN agent_license_allowed_users as ala on ala.agent_license_id=al.id AND ala.user_id='.$this->userId.'
							WHERE al.state="'.$state.'"
							Order By Rand()
							LIMIT 1';
				//echo('Query2: '.$query2.'<br>');
				$result2 = $this->runQuery ( $query2, $this->getDBConnection ()->getDBConnection () );
				$row2 = $result2->fetch_assoc ();
				if(isset($row2['agent_license_id'])){
					$agentLicenseId = $row2['agent_license_id'];
				}else{
					continue;
				}
				$bidPriceMinPercentage = ((float)$this->profileData['bid_price_min_percentage']);
				$bidPriceMinPercentage = ($bidPriceMinPercentage>1)? $bidPriceMinPercentage/100.00: $bidPriceMinPercentage;
				$minBidAmount = max(array(
				$this->profileData['bid_price_min'],
				$this->getBidPriceUsingNetToHudPercentage($price,$bidPriceMinPercentage)
				));
				$bidPriceMaxPercentage = ((float)$this->profileData['bid_price_max_percentage']);
				$bidPriceMaxPercentage = ($bidPriceMaxPercentage>1)? $bidPriceMaxPercentage/100.00: $bidPriceMinPercentage;
				$maxBidAmount = min(array(
				$this->profileData['bid_price_max'],
				$this->getBidPriceUsingNetToHudPercentage($price,$bidPriceMaxPercentage)
				));
				$bidPricePercentageIncrease = ((float)$this->profileData['bid_price_percentage_increase']);
				$bidPricePercentageIncrease = ($bidPricePercentageIncrease>1)? $bidPricePercentageIncrease/100.00: $bidPricePercentageIncrease;
				$bidIncrement = $this->profileData['bid_price_increase'];
				$submissionDate = date('Y-m-d h:i:s');
				//TODO change submission date to start with profile start date
				
				
				// Increase the submission date so it does fall on a weekend
				$time = strtotime($submissionDate);
				$dayOfWeek = (int )date('N',$time);
				while($dayOfWeek>5){
					$time = strtotime($submissionDate.' + 1 DAY');
					$submissionDate = date('Y-m-d h:i:s', $time);
					$dayOfWeek = (int )date('N',$time);
				};

				$roundTo2DecPlaces = array(
				&$minBidAmount,
				&$maxBidAmount,
				&$bidIncrement,
				&$bidPricePercentageIncrease
				);
				
			$len = count($roundTo2DecPlaces);
			while($len--){ 
			    $roundTo2DecPlaces[$len] = round($roundTo2DecPlaces[$len],2); 
			}
			
//				 echo('Case: '.$case.'<br>');
//				 echo('List Price: '.$price.'<br>');
//				 echo('Min Bid: '.$minBidAmount.'<br>');
//				 echo('Max Bid: '.$maxBidAmount.'<br>');
//				 echo('Bid Increment: '.$bidIncrement.'<br>');
//				 echo('Submission Date: '.$submissionDate.'<br><br><br>');
				
				
				for ($caseCount=0;$minBidAmount<=$maxBidAmount;$caseCount++ ){
					if (! isset ( $this->currentBids [$case] )) {
						$this->currentBids [$case] = array ();
					}
					$this->currentBids [$case][] = array(
					'id'=>'newBid_'.$case.'_'.$caseCount,
					'case'=>$case,
					'purchaser_type'=>$this->profileData['purchaser_type'],
					'bid_amount'=>$minBidAmount,
					'seller_closing_cost'=>$this->profileData['seller_closing_cost'],
					'broker_commission_cost'=>$this->profileData['broker_commission_cost'],
					'accept_as_backup_offer'=>$this->profileData['accept_as_backup_offer'],
					'scheduled_submission_time'=>$submissionDate
					
					);
					
					//Get The Next MinBid adding the Increment
					$bidPriceMinPercentage+=$bidPricePercentageIncrease;
					$minBidAmount = min(array(
					$minBidAmount+$bidIncrement,
					$this->getBidPriceUsingNetToHudPercentage($price,$bidPriceMinPercentage)
					));
					
					// Increase the date by 1 day
					do{
					$time = strtotime($submissionDate.' + 1 DAY');
					$submissionDate = date('Y-m-d h:i:s', $time);
					$dayOfWeek = (int )date('N',$time);
					}while($dayOfWeek>5);
					
					// Round the values to 2 decimal places
					$len = count($roundTo2DecPlaces);
					while($len--){ 
					    $roundTo2DecPlaces[$len] = round($roundTo2DecPlaces[$len],2); 
					}
					
					if($caseCount>10){
						//TODO: Check if the date has increased pass the end date
						
						break;
					}
				}
			}
		}
		
		//var_dump($this->currentBids);
		
		//die();
		
	}
	
	function getBidPriceUsingNetToHudPercentage($listPrice, $percentage){
		$percentage = ($percentage>1)? $percentage/100.0: $percentage;
		$sellerClosingCost = $this->getSellerClosingCost($listPrice,$this->profileData['seller_closing_cost_percentage'],$this->profileData['seller_closing_cost']);
		$brokerCommissionCost = $this->getBrokerCommission($listPrice,$this->profileData['broker_commission_cost_percentage'],$this->profileData['broker_commission_cost']);
		$bid =(($listPrice*$percentage)+$sellerClosingCost+$brokerCommissionCost)/(.97);
		return $bid;
		
	}
	
	function getSellerClosingCost($bidPrice, $sellerCommisionPercentage = .03, $sellerCommission){
		return $this->getBrokerCommission($bidPrice,$sellerCommisionPercentage,$sellerCommission);
	}
	
	function getBrokerCommission($bidPrice, $brokerCommissionPercentage = .03, $brokerCommission){
		if(!isset($brokerCommission)){
			$brokerCommission = $bidPrice*.03;
		}
		$brokerCommissionPercentage = ($brokerCommissionPercentage>1)? $brokerCommissionPercentage/100.0 : $brokerCommissionPercentage;
		return min(array(
		($bidPrice*.03),
		$bidPrice*$brokerCommissionPercentage,
		$brokerCommission
		)
		);
	}
	
	function saveProfile() {
		$params = $_REQUEST;
		if (count ( $params ) == 0) {
			return;
		}
		$tableFieldsWithValues = array ();
		$sql_link = $this->getDBConnection ()->getDBConnection ();
		$type = '';
		// Get all the user_bid_profile fields
		$tableFieldQuery = 'SHOW COLUMNS FROM user_bids_profiles where Field in (\'' . implode ( '\', \'', array_keys ( $params ) ) . '\')';
		$result = $this->runQuery ( $tableFieldQuery, $sql_link );
		//echo (mysqli_error ( $sql_link ));
		while ( ($row = $result->fetch_assoc ()) ) {
			$field = $row ['Field'];
			$columnType = $row ['Type'];
			if (isset ( $params [$field] )) {
				//echo($field.'='.$params[$field].'<br>');
				$paramValue = $params [$field];
				if (is_array ( $paramValue )) {
					$paramValue = json_encode ( $paramValue );
				}else{
					$paramValue = mysql_escape_string ( $paramValue );
				}
				$tableFieldsWithValues ['`'.$field.'`'] = $paramValue;
				if (stripos ( $columnType, 'var' ) !== false) {
					$type .= 's';
				} else if (stripos ( $columnType, 'float' ) !== false) {
					$type .= 'd';
				} else {
					$type .= substr ( $columnType, 0, 1 );
				}
			}
		}
		if (count ( $tableFieldsWithValues ) > 0) {
			$placeHolders = array_fill ( 0, count ( $tableFieldsWithValues ), '?' );
			$sql = "INSERT IGNORE INTO user_bids_profiles (" . implode ( ', ', array_keys ( $tableFieldsWithValues ) ) . ") VALUES (" . implode ( ', ', $placeHolders ) . ")";
			if (isset ( $this->profileId )) {
				$sql = "Update user_bids_profiles SET " . implode ( '=?, ', array_keys ( $tableFieldsWithValues ) ) . "=? WHERE id=" . $this->profileId;
			}
			//echo($sql."<br>");
			$sql_stmt = mysqli_prepare ( $sql_link, $sql );
			$stmtParams = array (&$type );
			foreach ( $tableFieldsWithValues as &$value ) {
				$stmtParams [] = &$value;
			}
			
			//echo('Statement Params:<br>');
			//var_dump($stmtParams);
			//echo('<br>');
			

			call_user_func_array ( array ($sql_stmt, 'bind_param' ), $stmtParams );
			$sql_stmt->execute ();
			
			if(mysqli_errno($sql_link)){
				echo('SQL Error: '.mysqli_error($sql_link));
			}
			
			// Get the new profile ID from the executed statement
			if ($sql_stmt->insert_id > 0) {
				$this->profileId = $sql_stmt->insert_id;
			}
			
			$sql_stmt->close();
			
		//printf("Error(%d): %s .\n", $sql_stmt->errno, $sql_stmt->error);
		}
		
		// TODO: check to see if we need to save new user address
		
		
		// Save any Updated or New Bid Data
		$this->saveBids();
		

		// Reload the profile data
		$this->loadBidProfile ( $this->profileId );
	}
	
	function saveBids(){
		$params = $_REQUEST;
		if (count ( $params ) == 0) {
			return;
		}
		
		if(!isset($params['bid'])){
			//echo('<h1><b>No Bids To Save</b></h1><br>');
			return;
		}

		$bidData = $params['bid'];
		$sql_link = $this->getDBConnection ()->getDBConnection ();
		
		foreach ($bidData as $bidId => $params){
			
			$isNewBid = false;
			if(stripos($bidId,'new')!==false){
				$isNewBid = true;
			}
			
			if(!isset($params['user_confirmed'])){
				$params['user_confirmed'] = 0;
			}
		
			$tableFieldsWithValues = array ();
			$type = '';
			// Get all the user_bid_profile fields
			$tableFieldQuery = 'SHOW COLUMNS FROM user_bids where Field in (\'' . implode ( '\', \'', array_keys ( $params ) ) . '\')';
			$result = $this->runQuery ( $tableFieldQuery, $sql_link );
			//echo (mysqli_error ( $sql_link ));
			while ( ($row = $result->fetch_assoc ()) ) {
				$field = $row ['Field'];
				$columnType = $row ['Type'];
				if (isset ( $params [$field] )) {
					//echo($field.'='.$params[$field].'<br>');
					$paramValue = $params [$field];
					if (is_array ( $paramValue )) {
						$paramValue = json_encode ( $paramValue );
					}else{
						$paramValue = mysql_escape_string ( $paramValue );
					}
					$tableFieldsWithValues ['`'.$field.'`'] = $paramValue;
					if (stripos ( $columnType, 'var' ) !== false || stripos ( $columnType, 'date' ) !== false) {
						$type .= 's';
					} else if (stripos ( $columnType, 'float' ) !== false) {
						$type .= 'd';
					} else {
						$type .= substr ( $columnType, 0, 1 );
					}
				}
			}
			if (count ( $tableFieldsWithValues ) > 0) {
				
				// Add the additional fields if this is a new bid
				if ($isNewBid) {
					// Skip if user has not confirmed this new bid entry
					if(!isset($tableFieldsWithValues['`user_confirmed`'])|| $tableFieldsWithValues['`user_confirmed`']!=1){
						echo($bidId." is Not user confirmed.<br>");
						continue;
					}
					
					// Get the rest of the bid info needed to make insert
					$tableFieldsWithValues['`user_id`']= $this->profileData['user_id'];
					$tableFieldsWithValues['`user_address_id`']= $this->profileData['user_address_id'];
					$tableFieldsWithValues['`user_purchase_id`']= $this->profileData['user_purchase_id_id'];
					$tableFieldsWithValues['`user_bid_profile_id`']= $this->profileData['id'];
					
					$query3 = 'Select al.agent_id as agent_id, al.id as license_id, b.id as broker_id 
							from property_list as pl
							INNER JOIN agent_license as al ON pl.state=al.state 
							INNER JOIN agent_license_allowed_users as ala on ala.agent_license_id=al.id AND ala.user_id='.$this->userId.'
							INNER JOIN agents as a ON a.id=al.agent_id
							INNER JOIN brokers as b ON b.id=a.broker_id
							 
							WHERE pl.case="'.$tableFieldsWithValues['`case`'].'"
							Order By Rand()
							LIMIT 1';
					//echo('<br><br>Query3: '.$query3.'<br>');
					$result3 = $this->runQuery ( $query3, $this->getDBConnection ()->getDBConnection () );
					$row3 = $result3->fetch_assoc ();
					if(isset($row3['agent_id'])){
						$agentId = $row3['agent_id'];
					}else{
						//echo($bidId." has no agent id.<br>");
						//echo('<br><br>Query3: '.$query3.'<br>');
						continue;
					}
					if(isset($row3['license_id'])){
						$licenseId = $row3['license_id'];
					}else{
						//echo($bidId." has not license id.<br>");
						continue;
					}
					if(isset($row3['broker_id'])){
						$brokerId = $row3['broker_id'];
					}else{
						//echo($bidId." has not broker id.<br>");
						continue;
					}
					$tableFieldsWithValues['`agent_id`']=$agentId;
					$tableFieldsWithValues['`license_id`']=$licenseId;
					$tableFieldsWithValues['`broker_id`']=$brokerId;
					$tableFieldsWithValues['`finance_type`']= $this->profileData['finance_type'];
					
					$type .= 'iiiiiiii';
					
				}
				
//				echo('Table Values For Bid ID: '.$bidId.'<br>');
//				var_dump($tableFieldsWithValues);
//				echo('<br>');
				
				$placeHolders = array_fill ( 0, count ( $tableFieldsWithValues ), '?' );
				$sql = "INSERT IGNORE INTO user_bids (" . implode ( ', ', array_keys ( $tableFieldsWithValues ) ) . ") VALUES (" . implode ( ', ', $placeHolders ) . ")";
				if (!$isNewBid) {
					$sql = "Update user_bids SET " . implode ( '=?, ', array_keys ( $tableFieldsWithValues ) ) . "=? WHERE id=" . $bidId;
				}
//				echo('<br>'.$sql."<br>");
				$sql_stmt = mysqli_prepare ( $sql_link, $sql );
				$stmtParams = array (&$type );
				foreach ( $tableFieldsWithValues as &$value ) {
					$stmtParams [] = &$value;
				}
				
//				echo('Statement Params:<br>');
//				var_dump($stmtParams);
//				echo('<br>');

				call_user_func_array ( array ($sql_stmt, 'bind_param' ), $stmtParams );
				
//				var_dump($sql_stmt);
				
				$sql_stmt->execute ();
				
				if(mysqli_errno($sql_link)){
					echo('<br>SQL Error: '.mysqli_error($sql_link).'<br>');
				}
				
				$sql_stmt->close();
				
			}	
		}
	}
}

$obj = new HHSBidsProfile ( );
?>